//
//  HBJNetworkManager.swift
//  zhihuifan
//
//  Created by apple on 2017/8/23.
//  Copyright © 2017年 youyou. All rights reserved.
//

import Foundation
import Alamofire
fileprivate let BaseURL = "http://www.xftb168.com/"

class HBJNetworkManager: NSObject {
    static let shared:HBJNetworkManager = {
       let instance =  HBJNetworkManager()
        return instance
    }()
    //访问令牌
    var access_token:String?
    func request(url:String,
                 method:HTTPMethod,
                 paramters:[String:Any]?,
                 completion:@escaping (_ json:[String:AnyObject]?,_ isSuccess:Bool)->())->(){
    Alamofire.request(BaseURL + url,
                      method: method,
                      parameters: paramters,
                      encoding: JSONEncoding.default).responseJSON
        { (responseData) in
        
        switch responseData.result.isSuccess {
        case true:
            guard let data = responseData.data ,
                let json = try? JSONSerialization.jsonObject(with:data, options: []) as? [String:AnyObject],
            let code:String? = json?["code"] as? String
                else {
                return
            }
       //FIXME: -登陆超时处理
            if code == "-1"{
                
            }else{
                completion(json, true)
            }
        case false:
            print(responseData.result.error ?? Error.self)
        }

        }
    }
    func tokenRequest(url:String,
                      method:HTTPMethod,
                      paramters:[String:AnyObject]?,
                      completion:@escaping (_ json:[String:AnyObject]?,_ isSuccess:Bool)->())->(){
        guard let accesstoken = access_token else {
            //FIXME:未登陆
            completion(nil,false)
            return
        }
        var parameter = paramters
        if parameter == nil {
            parameter = [String:AnyObject]()
        }
        parameter?["tokenid"] = accesstoken as AnyObject
        tokenRequest(url: url,
                     method: method,
                     paramters: paramters,
                     completion: completion)
    }
}
